import os
import random
from PIL import Image
from torchvision import transforms
import torch

class CustomDataset(torch.utils.data.Dataset):
    def __init__(self, root_dir, transform=None):
        self.root_dir = root_dir
        self.transform = transform
        self.classes = os.listdir(root_dir)

    def __len__(self):
        return len(self.classes) * 10  # 调整为适合你数据集大小的数值

    def __getitem__(self, idx):
        random_value = random.randint(0, 100)
        if random_value > 50:
            # 同类图像
            class_folder = random.choice(self.classes)
            img_files = os.listdir(os.path.join(self.root_dir, class_folder))
            img1_file, img2_file = random.sample(img_files, 2)
            label = 1
            img1 = Image.open(os.path.join(self.root_dir, class_folder, img1_file))
            img2 = Image.open(os.path.join(self.root_dir, class_folder, img2_file))
        else:
            # 异类图像
            class1_folder, class2_folder = random.sample(self.classes, 2)
            img1_file = random.choice(os.listdir(os.path.join(self.root_dir, class1_folder)))
            img2_file = random.choice(os.listdir(os.path.join(self.root_dir, class2_folder)))
            label = 0
            img1 = Image.open(os.path.join(self.root_dir, class1_folder, img1_file))
            img2 = Image.open(os.path.join(self.root_dir, class2_folder, img2_file))

        if self.transform:
            img1 = self.transform(img1)
            img2 = self.transform(img2)

        return (img1, img2), torch.tensor(label, dtype=torch.float32)

